<template>
  <div class="table">
    <div class="tableData">
      <el-table 
        :data="filterTableData" 
        style="width: 100%" 
        highlight-current-row="true"
        :header-row-style="{'color': '#000'}"
      >
        <el-table-column  type="index" :index="1" />
        <el-table-column label="用户名" prop="username" />
        <el-table-column label="邮箱" prop="email" />
        <el-table-column label="电话" prop="phonenumber" />
        <el-table-column label="头像" width="180">
          <template #default="scope">
            <div style="display: flex; align-items: center">
              <el-image 
                v-if="scope.row.avatar" 
                :src="BASE_URL + scope.row.avatar" 
                :style="{ width: '60px', height: '60px', borderRadius: '50%' }">
              </el-image>
              <div v-else style="width: 60px; height: 60px; display: flex; justify-content: center; align-items: center; border-radius: 50%; background-color: #f2f2f2; color: #999; font-size: 14px;">
                none
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="备注" prop="remark" />
        <el-table-column align="right">
          <template #header>
            <el-input class="search-input" v-model="search" size="small" placeholder="用户名搜索"/>
            <el-button class="addUser-button" type="primary" size="small">新增用户</el-button>
          </template>
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="demo-pagination-block">
      <el-pagination
        v-model:current-page="currentPage2"
        v-model:page-size="pageSize2"
        :page-sizes="[20, 50, 100, 500]"
        :small="small"
        :disabled="disabled"
        :background="background"
        layout="total,sizes, prev, pager, next"
        :total="totalItems"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
  <div class="edituser-table" >
    <EditUser 
      :editCenterDialogVisible="editCenterDialogVisible" 
      :userInfo="userInfo" 
      @update:editCenterDialogVisible="updateDialogClose" 
      @saveUserInfo="saveUserInfo"
    />
  </div>
  <div class="addtuser-table"></div>
</template>

<script setup>
import { computed, ref, onMounted } from 'vue'
import axios from 'axios'  // 导入axios用于发送HTTP请求
import { BASE_URL } from '@/config';
import AddUser from './addUser.vue';
import EditUser from './editUser.vue';
import { ElMessage } from 'element-plus'


// 数据定义
const search = ref('')
const tableData = ref([])  // 用于存储从接口获取的用户数据
const totalItems = ref(0)  // 存储分页的总数

const currentPage2 = ref(1)
const pageSize2 = ref(20)
const background = ref(false)
const disabled = ref(false)
const small = ref(false)

// 计算属性，过滤数据
const filterTableData = computed(() =>
  tableData.value.filter(
    (data) =>
      !search.value ||
      data.username.toLowerCase().includes(search.value.toLowerCase())
  )
)

// 请求用户数据的函数
const fetchUserData = async (page = 1, size = 20) => {
  try {
    const response = await axios.get('user/', {
      params: { page, size }  // 传递分页参数
    })
    tableData.value = response.data.data  // 更新表格数据
    // totalItems.value = response.data.data.  // 更新总数据量
    totalItems.value = Object.keys(response.data.data).length  // 更新总数据量
    console.log(totalItems.value)
  } catch (error) {
    console.error('Failed to fetch user data:', error)
  }
}

// 组件挂载时请求数据
onMounted(() => {
  fetchUserData(currentPage2.value, pageSize2.value)
})

// 分页变更事件
const handleSizeChange = (val) => {
  pageSize2.value = val
  fetchUserData(currentPage2.value, val)
}

const handleCurrentChange = (val) => {
  currentPage2.value = val
  fetchUserData(val, pageSize2.value)
}


const editCenterDialogVisible = ref(false) // 控制展示编辑弹窗
const userInfo = ref()
// 编辑事件
const handleEdit = (row) => {
  editCenterDialogVisible.value = true
  userInfo.value = row
}
// 监听子组件关闭弹窗
const updateDialogClose = (bool) =>{
  editCenterDialogVisible.value=bool
}

// 监听子组件修改后传递新数据并发送请求
const saveUserInfo = async(updatedUserInfo)=>{
  const id = updatedUserInfo.id
  const data = {
    username:updatedUserInfo.username,
    email:updatedUserInfo.email,
    phonenumber:updatedUserInfo.phonenumber,
    remark:updatedUserInfo.remark,
  }
  try {
    const response = await axios.put(`/user/${id}/`, data);
    if (response.data.code === 200) {
      console.log('更新成功', response.data);
      // 可以在这里处理响应数据，例如更新本地列表，显示提示等
      // 更新数据
      fetchUserData()
        ElMessage({
          message: response.data.msg,
          type: 'success',
        })
    }else{
          ElMessage({
          message: `删除失败，${response.data.msg}`,
          type: 'error',
      })
    }
  } catch (error) {
    console.error('更新失败', error);
    ElMessage({
          message: `更新失败`,error,
          type: 'error',
      })
  }
};


// 删除用户信息
const handleDelete = async(id) => {
  try{
    const response = await axios.delete(`user/${id}`);
    console.log("id",id)
    if (response.data.code === 200) {
      console.log('删除用户成功', response.data);
      // 可以在这里处理响应数据，例如更新本地列表，显示提示等
      // 更新数据
      fetchUserData()
      ElMessage({
        message: response.data.msg,
        type: 'success',
      })
    }else{
        ElMessage({
        message: response.data.msg,
        type: 'error',
      })
    }
  }catch(error){
    ElMessage.error('请求失败，请稍后再试');
  }
}

// 新增用户



</script>

<style scoped>
.demo-pagination-block {
  display: flex;
  justify-content: flex-end;  /* 使用flex布局右对齐 */
  margin-top: 10px;
}

.search-input {
  width: 120px;
  margin-right: 15px;
}

.addUser-button {
  width: 100px;
}
</style>
